<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Controller_EditTag extends Paylog_Abstract_Controller
{
	protected $groupHand = null;
	protected $tagHand   = null;
	protected $tagObj    = null;
	protected $tagId     = null;
	protected $input     = array();
	protected $errors    = array();

	public function __construct()
	{
		parent::__construct();

		$this->groupHand = new Paylog_Object_GroupHandler;
		$this->tagHand   = new Paylog_Object_TagHandler;
		$this->tagId     = intval(Paylog::get('id'));
		$this->tagObj    = $this->tagHand->load($this->tagId);

		$name    = $this->tagObj->getVar('name');
		$groupId = $this->tagObj->getVar('group_id');
		$weight  = $this->tagObj->getVar('weight');

		$name    = Paylog::post('name', $name);
		$groupId = Paylog::request('group_id', $groupId);
		$weight  = Paylog::post('weight', $weight);

		$this->input = array(
			'name'     => $name,
			'group_id' => $groupId,
			'weight'   => $weight,
		);
	}

	public function main()
	{
		$this->_validateAccess();

		if ( Paylog::post('save') )
		{
			try
			{
				$this->_save();
			}
			catch ( Exception $e )
			{
				$this->_default();
			}
		}
		else
		{
			$this->_default();
		}
	}

	protected function _save()
	{
		$token = Paylog::post('token');

		if ( !Paylog_Class_Ticket::check($token) )
		{
			$this->errors[] = Paylog::msg("Ticket Error");
			throw new Exception();
		}

		$this->tagObj->setVar('name', $this->input['name']);
		$this->tagObj->setVar('group_id', $this->input['group_id']);
		$this->tagObj->setVar('weight', $this->input['weight']);

		if ( $this->tagHand->save($this->tagObj) )
		{
			$extra = array('group_id' => $this->input['group_id']);
			Paylog::redirect("Tags successly updated.", Paylog::$dirname, 'edit_tag', null, $extra);
		}
		else
		{
			$this->errors[] = Paylog::msg("Tags updating failed.");
			throw new Exception();
		}
	}

	protected function _default()
	{
		$groupObjs = $this->groupHand->loads();

		$this->output['groups'] = array();

		foreach ( $groupObjs as $groupObj )
		{
			$this->output['groups'][] = array(
				'id'   => $groupObj->getVar('id'),
				'name' => $groupObj->getVar('name'),
			);
		}

		$this->output['input']  = $this->input;
		$this->output['errors'] = $this->errors;
		$this->output['token']  = Paylog_Class_Ticket::issue();

		$this->_view();
	}

	protected function _validateAccess()
	{
		if ( $this->tagId < 0 )
		{
			Paylog::redirect("Tag ID is invalid.");
		}

		if ( $this->tagId > 0 and !$this->tagHand->isIdExists($this->tagId) )
		{
			Paylog::redirect("Such a tag does not exists.");
		}

		if ( $this->groupHand->count() < 1 )
		{
			Paylog::redirect("Please create groups.", Paylog::$dirname, 'edit_group');
		}
	}
}

?>
